<!--
	全国承灾体易损性数据
	Created by Penglei on 2023/08/10
-->
<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item height-300">
          <subheadings name="单体建筑物易损性数量" />
          <SingleBuilding></SingleBuilding>
        </div>
        <div class="app-left-item height-300">
          <subheadings :name="province + '建筑物综合易损性曲线'" />
          <FragilityCurve :province="province" @onChangeProvince="onChangeProvince"></FragilityCurve>
        </div>
        <div class="app-right-item height-300">
          <subheadings name="全国建筑物抗震设防统计" />
          <ComprehensiveStatistics></ComprehensiveStatistics>
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline name="全国承灾体易损性数据" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '-30px', left: '42px' }" />
          <Legend :style="{ bottom: '150px' }" startColor="#92A0F0" endColor="rgba(15, 40, 160, 1)"></Legend>
          <OlMap :refId="'vulnerability'" style="height: 100%" @getMap="getMap" @mapClick="mapClick"></OlMap>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item height-300">
          <subheadings name="生命线工程及重大基础设施易损性数量" />
          <LifelineEngineer></LifelineEngineer>
        </div>
        <div class="app-left-item height-400">
          <subheadings name="易损性数据分省统计" />
          <ProvincialStatistics @onChangeProvince="onChangeProvince"></ProvincialStatistics>
        </div>
        <div class="app-right-item height-200">
          <subheadings name="全国承灾体易损性访问统计" />
          <AccessStatistics class="panel-access-statistics"></AccessStatistics>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Vulnerability">
// 单体建筑物易损性数量
import SingleBuilding from './components/SingleBuilding';
// 易损性数据分省统计
import ProvincialStatistics from './components/ProvincialStatistics';
// XXX省建筑物综合易损性曲线
import FragilityCurve from './components/FragilityCurve';

// 生命线工程及重大基础设施易损性数量
import LifelineEngineer from './components/LifelineEngineer';
// 全国建筑物抗震设防统计
import ComprehensiveStatistics from './components/ComprehensiveStatistics';
// 访问统计
import AccessStatistics from './components/AccessStatistics';
// 系统选择
import SystemSelect from '@/components/SystemSelect';
import { getBaseDir } from '@/map/projMap.js';
import { getCompleteness } from '@/api/vulnerability';

// 建筑物综合易损性曲线省份
let province = ref('');
// 省份改变
const onChangeProvince = (val) => {
  province.value = val;
};

// start
import OlMap from '@/components/Olmap';
import Legend from './components/Legend.vue';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon, Text } from 'ol/style';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
// start
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { useRouter } from 'vue-router';
// end
// start
const mapInstance = ref(null);
const provinceLayer = ref(null);
const chinaProvinceFeatures = ref(null);
const router = useRouter();

const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);
  createProvinceLayer();

  setupSelectInteraction();
};

const setupSelectInteraction = () => {
  mapInstance.value.on('click', (event) => {
    const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
    //点中了地图区域
    if (features.length > 0) {
      router.push({ path: '/vulnerability/subpage1' });
    }
  })
}

const mapClick = () => {
  //router.push({ path: '/vulnerability/subpage1' });
};

let colorMap = new Map();
// 创建省份样式的函数
const createProvinceStyle = (feature) => {
  let randomColor;
  if (colorMap.has(feature.get('adcode'))) {
    randomColor = colorMap.get(feature.get('adcode'));
  } else {
    randomColor = getColors(feature.get('adcode'));
    colorMap.set(feature.get('adcode'), randomColor);
  }
  return new Style({
    fill: new Fill({ color: randomColor }),
    // stroke: new Stroke({ color: 'blue', width: 1 }),
    text: new Text({
      font: '10px Calibri,sans-serif',
      fill: new Fill({ color: '#fff' }),
      text: feature.get('name'),
    }),
  });
};
const getColors = (adcode) => {
  if ([110000, 150000, 320000, 540000].includes(adcode)) {
    return 'rgba(95,133,255,1)';
  } else if ([130000, 210000, 220000, 230000, 330000, 440000, 450000].includes(adcode)) {
    return 'rgb(124, 151, 240)';
  } else if ([, 140000, 410000, 610000, 370000, 420000, 350000, 360000].includes(adcode)) {
    return 'rgb(170, 186, 237)';
  } else if ([510000, 520000].includes(adcode)) {
    return 'rgb(5, 24, 86)';
  } else if ([640000].includes(adcode)) {
    return 'rgb(8, 39, 142)';
  } else {
    return 'rgb(26, 72, 225)';
  }
};
const addCompletenessData = () => {
  getCompleteness().then((res) => {
    console.log('res---', res);
    let data = res.data;
    if (data && data.length > 0) {
      data.forEach((item) => {
        let feature = chinaProvinceFeatures.value.find((feature) => {
          return feature.get('adcode') == item.code;
        });
        if (feature) {
          feature.setStyle(getProviceStyle(feature, item.completeness));
        }
      });
    }
  });
};
const getProviceStyle = (feature, completeness) => {
  // color:rgb(170, 186, 237),rgb(124, 151, 240),rgba(95,133,255,1),rgb(8, 39, 142),rgb(5, 24, 86)
  let color = getColor(completeness);
  return new Style({
    fill: new Fill({ color: color }),
    stroke: new Stroke({ color: 'rgba(10, 22, 139, 1)', width: 1 }),
    text: new Text({
      font: '10px Calibri,sans-serif',
      fill: new Fill({ color: '#fff' }),
      text: feature.get('name'),
    }),
  });
};
const getColor = (value) => {
  var color = {
    0: 'rgba(146, 160, 240, 1)',
    1: 'rgba(95, 133, 255, 1)',
    2: 'rgba(48, 96, 255, 1)',
    3: 'rgba(26, 66, 194, 1)',
    4: 'rgba(15, 40, 160, 1)',
  };

  const intervals = [0, 0.2, 0.4, 0.6, 0.8, 1.0];
  for (let i = 0; i < intervals.length - 1; i++) {
    if (value <= intervals[i + 1]) {
      return color[i];
    }
  }
  return 'rgb(26, 72, 225)';
};
// 创建图层的函数
const createProvinceLayer = () => {
  provinceLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 1,
    // style: function (feature) {
    //   return createProvinceStyle(feature);
    // },
  });
  mapInstance.value.addLayer(provinceLayer.value);
  addChinaProvinceFeature();
};
const addChinaProvinceFeature = () => {
  fetch(getBaseDir('china.json'))
    .then((response) => response.json()) // 将响应解析为 JSON 数据
    .then((geojson) => {
      // 使用 GeoJSON 格式解析器将数据转换为 Features
      const geojsonFormat = new GeoJSonFormat();
      chinaProvinceFeatures.value = geojsonFormat.readFeatures(geojson);
      chinaProvinceFeatures.value.forEach((feature) => {
        feature.setStyle(
          new Style({
            stroke: new Stroke({
              color: 'rgba(10, 22, 139, 1)',
              width: 1,
            }),
            text: new Text({
              font: '10px Calibri,sans-serif',
              fill: new Fill({ color: '#fff' }),
              text: feature.get('name'),
            }),
          })
        );
      });
      provinceLayer.value.getSource().addFeatures(chinaProvinceFeatures.value);
      addCompletenessData();
    })
    .catch((error) => {
      console.error('Error fetching or processing GeoJSON:', error);
    });
};
// end
</script>

<style scoped lang="scss">
.app-container {
  min-height: 1080px;
}

.app-map {
  width: 960px;
  height: 100%;
  overflow: visible;
}

// 访问统计
.panel-access-statistics {
  padding-top: 30px;

  :deep(.visits-count) {
    height: 80px;

    .visits-count-number {
      height: 40px;
      line-height: 40px;
      margin-top: 8px;
    }
  }
}

// 模块高度
.height-200 {
  height: 200px;
}
.height-300 {
  height: 300px;
}
.height-400 {
  height: 400px;
}
</style>
